<?php
/**
 * @copyright   Copyright (c) 2018 http://www.brsttech.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 后台管理基础控制器
 */
namespace app\common\controller;
use think\Controller;
use think\facade\Hook;
use think\facade\Session;

class Admin extends Controller {

    const session_scope = 'SmartWechatAdmin';  //SESSION作用域
    const session_name  = 'admin';  //SESSION值
 
    protected function initialize()
    {
        Admin::isLogin(); //判断是否登录
    }

    /**
     * 判断是否有权限
     * @return boolean [description]
     */
    protected function isAuth(string $access_path,$is_json = false){
        $result = Hook::listen('check_auth',$access_path,true);
        if($result) return true;
        if($is_json){
            return json(['code' => 0,'msg' => '您没有权限访问']);
        }
        return $this->error('您没有权限访问');
    }
    
    /**
     * 判断管理员是否登录
     * @access protected
     * @return boolean
     */
    protected function isLogin(){
        //不需要登录验证的页面
        $noLogin = ['admin' =>['Login'=>['index','wechat','logout'],'Regist' => ['index']]];
        //当前请求方法
        $module     = $this->request->module();
        $controller = $this->request->controller();
        $action     = $this->request->action();
        //如果当前访问是无需登录验证则直接返回   
        if(isset($noLogin[$module])){
            if(isset($noLogin[$module][$controller]) && in_array($action, $noLogin[$module][$controller])){
                return true;
            }
        }
        if(!Session::has(self::session_name,self::session_scope)){
            Admin::setlogoutSession(); 
            $this->redirect(url('admin/login/index'),302);
        }
        return true;
    }

    /**
     * 获取Session
     * @access public
     */
    public function getLoginSession(){
        return Session::get(self::session_name,self::session_scope);
    } 
    
    /**
     * 设置登录Session
     * @access public
     */
    protected function setLoginSession($param){
        $data = [
            'group_id'   => $param['group_id'],
            'username'   => $param['username'],
            'admin_id'   => $param['id'],
            'login_time' => time(),
        ];
        return Session::set(self::session_name,$data,self::session_scope);
    }

    /**
     * 退出Session
     * @access public
     */
    protected function setlogoutSession(){
        return Session::delete(self::session_name,self::session_scope);
    }    
}
